#!/bin/bash
#export OPENAI_EMAIL=eric275043398@gmail.com
#export OPENAI_PASSWORD=
#export OPENAI_MFA_CODE='1'
#export CHATGPT_API_PREFIX="http://127.0.0.1:9091"
#export USER_CONFIG_DIR=/tmp/chatgpt41
#export PROXY= #socks5://100.91.60.131:25344,http://127.0.0.1:24002
#export TOKEN_API=http://127.0.0.1:9901

PORT=${PORT:-8009}
name="pandora$PORT"

if [ ! -d "$USER_CONFIG_DIR" ]; then
  # 如果文件夹不存在，创建它
  mkdir -p "$USER_CONFIG_DIR"
  echo "文件夹已创建"
fi

start_processes() {
        exec pandora -s 0.0.0.0:$PORT --name $name
}

stop_processes() {
    pkill -TERM -f $name
}

download_token() {
#  wget -O "$USER_CONFIG_DIR/access_token.dat" "$TOKEN_API/func/gptToken?id=17"
  python3 <<END
import requests

# 定义请求的URL
url = "$TOKEN_API/func/gptToken?email=$OPENAI_EMAIL"

# 发送HTTP GET请求
response = requests.get(url)

# 检查响应状态码
if response.status_code == 200:
    # 保存响应内容到文件
    with open("$USER_CONFIG_DIR/access_token.dat", "wb") as file:
        file.write(response.content)
else:
    print(f"HTTP请求失败，状态码: {response.status_code}")
END
}

trap 'stop_processes' EXIT

download_token

start_processes

while true; do
    sleep 1
done
